<template>
    <div>
        <div class="container">
            <div class="body">
                <h1>后台管理系统</h1>
                <el-form ref="form" :model="form" :rules="rules" status-icon label-width="80px"
                    style="text-align: left;">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="form.username" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="form.password" show-password clearable> </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm">登录</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            form: {
                username: 'admin',
                password: '123456'
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 20, message: '用户名请控制在5-20个字符', trigger: 'blur' },
                    { validator: this.AntiSqlValid, trigger: 'blur' }],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { validator: this.AntiSqlValid, trigger: 'blur' }]
            }
        }
    },
    methods: {
        //过滤特殊字符 
        AntiSqlValid(rule, value, callback) {
            const re = /\,|\'|\;|\$/g;
            if (re.test(value)) {
                callback('请输入合法数据')
            } else {
                callback()
            }
        },
        submitForm() {
            //表单数据验证 
            this.$refs.form.validate(async (valid) => {
                //valid为验证结果，true符合规则,false不符合规则 
                if (valid) {
                    //将用户名和密码发到服务端 
                    const result = await this.$http.post('/admCkLogin', this.form)
                    console.log(result)
                    if (result.data.status === 'success') {
                        //弹出登录成功提示 
                        this.$message.success('登录成功')
                        //将用户信息存入缓存 
                        localStorage.setItem('admin', JSON.stringify(result.data.info))
                        //跳转至管理后台主页 
                        this.$router.push({ name: 'Home' })
                    } else { this.$message.error('登录失败') }
                } else { this.$message.error('登录失败') }
            })
        }
    }
}

</script>

<style lang="scss" scoped>
.container {
    background-image: url('../assets/78277b5005f7c2cbd4cbada8e565bb76.jpeg');
    width: 100vw;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;

    .body {
        background-color: #fff;
        padding: 30px 50px;
        border-radius: 20px;
    }
}
</style>